package vip.aster.framework.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import vip.aster.framework.security.entity.SecurityUser;
import vip.aster.framework.security.entity.UserDetail;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * mybatis-plus自动填充字段
 *
 * @author Aster
 * @since 2023/11/24 15:18
 */
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {

    private final static String CREATE_TIME = "createTime";
    private final static String CREATE_BY = "createBy";
    private final static String UPDATE_TIME = "updateTime";
    private final static String UPDATE_BY = "updateBy";
    private final static String VERSION = "version";

    @Override
    public void insertFill(MetaObject metaObject) {
        UserDetail user = SecurityUser.getUser();
        if (user != null) {
            this.strictInsertFill(metaObject, CREATE_BY, String.class, user.getId());
            this.strictInsertFill(metaObject, UPDATE_BY, String.class, user.getId());
        }

        this.strictInsertFill(metaObject, CREATE_TIME, LocalDateTime::now, LocalDateTime.class);
        this.strictInsertFill(metaObject, UPDATE_TIME, LocalDateTime.class, LocalDateTime.now());

        this.strictInsertFill(metaObject, VERSION, Integer.class, 0);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        UserDetail user = SecurityUser.getUser();
        if (user != null) {
            this.strictUpdateFill(metaObject, UPDATE_BY, String.class, user.getId());
        }
        this.strictUpdateFill(metaObject, UPDATE_TIME, LocalDateTime.class, LocalDateTime.now());
    }
}
